package com.roc.web.action.estrn;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblTfrHisTrnLog;
import com.roc.service.IExcelService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Component
@Scope("prototype")
@Namespace("/ysbestrnlog")
public class YsbEstrnHisInfoAction extends PaginationBaseAction{

	private static final long serialVersionUID = -4049588019525630037L;

	private Logger logger=LogManager.getLogger(YsbEstrnHisInfoAction.class);
	
	private YsbEstrnHisInfoSearchCondition searchCondition;
	private InputStream excelFile;
	
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IExcelService excelService;
	@Autowired
	private IPowerInfoService powerInfoService;
	
	protected Map<String,String> respondeMap = ConfigProperties.getSysDB1("RESP_CD",false);
	protected Map<String,String> reversalMap=ConfigProperties.getReversalTypes();
	protected Map<String,String> tranMap = ConfigProperties.getSysDB1("TRANS_CD",false);
	
	
	@Action(value = "queryEstrnHisInfoJsp", results = { @Result(name = "success", location = "/pages/estrn/queryYsbEstrnHis.jsp")
				,@Result(name = "error", location = "/error.jsp")})
	public String queryEstrnHisInfoAction() throws Exception{
		logger.info("跳转到云商宝历史交易查询页面");
        Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
        /*if (!op.getRoleType().equals(Role.AGENT.getCode()) && !op.getRoleType().equals(Role.O_MANAGER.getCode())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}*/
        
        if(searchCondition==null){
			searchCondition=new YsbEstrnHisInfoSearchCondition();
		}
		
		searchCondition.setTranDate(Constance.formatDate("yyyyMMdd"));
		searchCondition.setMinDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
		searchCondition.setMaxDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
		org();
		return SUCCESS;
	}
	
	@Action(value = "queryEstrnHisList", results = { @Result(name = "success", location = "/pages/estrn/queryYsbEstrnHis.jsp")
           })
	//查询云商宝历史交易记录
	public String queryEstrnHisListAction() throws Exception{

		logger.info("查询云商宝历史交易记录");
        Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if(searchCondition==null){
				searchCondition=(YsbEstrnHisInfoSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new YsbEstrnHisInfoSearchCondition();
				}
			}
			logger.info("查询条件："+"交易日期："+searchCondition.getMinDate()+"-"+searchCondition.getMaxDate());
			if("".equals(Constance.Null2EmptyTrim(searchCondition.getMinDate())) || "".equals(Constance.Null2EmptyTrim(searchCondition.getMaxDate()))){
				logger.info("云商宝历史交易查询查询条件时间为空");
				return SUCCESS;
			}
			
			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
	        String superRole= map.get("superRole");
	        String opRealId =map.get("opRealId");
	        //当登录人员为代理商时，查询他的子代理
			searchCondition.setRoleType(superRole);
			if(Role.MERCHANT.getCode().equals(superRole)){
				searchCondition.setMerNo(logingMerchant.getAccountNo());
			}else if(Role.AGENT.getCode().equals(superRole)||Role.SFB_AGENT.getCode().equals(superRole)||Role.O_MANAGER.getCode().equals(superRole)){
					
				String agentId= opRealId;
				searchCondition.setAgentId(agentId);
					
			}else if(Role.AGENT_BUSS.getCode().equals(superRole)){
				searchCondition.setOpId(opRealId);
			}else if(Role.MARKET_DIRECT.getCode().equals(superRole) || Role.MARKET_LEAD.getCode().equals(superRole)){
				searchCondition.setMarketorId(opRealId);
			}
			
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			List<TblTfrHisTrnLog> tftList = new ArrayList<TblTfrHisTrnLog>();
			dealTheSearchRsList(tftList,searchRsList);
		
			getRequest().setAttribute("tftList", tftList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			org();
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
			
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	
	private void dealTheSearchRsList(List<TblTfrHisTrnLog> tftList,
			List<Object> searchRsList) {
		try {
			
	    Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
	    
		if(searchRsList!=null&&searchRsList.size()>0){
			Iterator iterator=searchRsList.iterator();
			while (iterator.hasNext()) {
				Object[] obj= (Object[])iterator.next();
				TblTfrHisTrnLog t = new TblTfrHisTrnLog();
				//主账号
				if("1".equals(logingMerchant.getAgentType())){
					t.setPriAcctNo(Constance.Null2EmptyTrim(obj[5]));
				}else{
					t.setPriAcctNo(Utils.dealCardNoTwo(Constance.Null2EmptyTrim(obj[5])));
				}
				
				
				t.setTransDt(Constance.Null2EmptyTrim(obj[0]));
				t.setTransMt(Constance.Null2EmptyTrim(obj[1]));
				t.setTranTp(Constance.Null2EmptyTrim(obj[2]));
				t.setRespCd(Constance.Null2EmptyTrim(obj[3]));
				t.setTransSt(Constance.Null2EmptyTrim(obj[4]));
				t.setCardType(Constant.CARD_CLASS_MAP.get(Constance.Null2EmptyTrim(obj[6])));
				t.setPmtNo(Constance.Null2EmptyTrim(obj[7]));
				t.setMchntNmConv(Constance.Null2EmptyTrim(obj[9]));
				t.setMchntCd(Constance.Null2EmptyTrim(obj[10]));
				t.setTermId(Constance.Null2EmptyTrim(obj[11]));
				t.setMaTransSeq(Long.parseLong(Constance.Null2EmptyTrim(obj[12])));
				t.setRetriRefNo(Constance.Null2EmptyTrim(obj[13]));
				t.setRespName(respondeMap.get(Constance.Null2EmptyTrim(obj[3])));
				t.setTransInf(tranMap.get(Constance.Null2EmptyTrim(obj[15])));
				t.setMchntCdConv(Constance.Null2EmptyTrim(obj[17]));
				t.setRetriRefNoConv(Constance.Null2EmptyTrim(obj[18]));
				String tra = Constance.Null2EmptyTrim(obj[8]);
				if("".equals(tra)){
					t.setTransAt("0.00");
				}else{
					BigDecimal btra = new BigDecimal(tra);
					BigDecimal bb = new BigDecimal(100);
					BigDecimal bres = btra.divide(bb,2,BigDecimal.ROUND_HALF_UP); 
					t.setTransAt(bres.toString());
				}
				
				String posEntrymd = Constance.Null2EmptyTrim(obj[14]);
				t.setPosEntryMdCd(posEntrymd);
				String cardClass = Constance.Null2EmptyTrim(obj[6]);
				if(posEntrymd.length()<3){
					t.setPosEntryMdCdName("未知");
				}else if("02".equals(posEntrymd.substring(0, 2))){
					t.setPosEntryMdCdName("磁条卡");
				}else if("05".equals(posEntrymd.substring(0, 2))){
					t.setPosEntryMdCdName("芯片插卡");
				}else if("07".equals(posEntrymd.substring(0, 2))){
					if("".equals(cardClass)){
						t.setPosEntryMdCdName("未知");
					}else if("0".equals(cardClass.substring(0, 1))){
						t.setPosEntryMdCdName("芯片非接");
					}else if("1".equals(cardClass.substring(0, 1))){
						t.setPosEntryMdCdName("芯片云闪付");
					}
				}else if("98".equals(posEntrymd.substring(0, 2))){
					if("".equals(cardClass)){
						t.setPosEntryMdCdName("未知");
					}else if("0".equals(cardClass.substring(0, 1))){
						t.setPosEntryMdCdName("芯片非接");
					}else if("1".equals(cardClass.substring(0, 1))){
						t.setPosEntryMdCdName("芯片云闪付");
					}
				}

				t.setMaTransCd(Constance.Null2EmptyTrim(obj[15]));
				
				if("1171".equals(t.getMaTransCd())||"1011".equals(t.getMaTransCd())||"4011".equals(t.getMaTransCd())||"2011".equals(t.getMaTransCd())||
				   "1161".equals(t.getMaTransCd())||"1191".equals(t.getMaTransCd())||"1261".equals(t.getMaTransCd())||"1291".equals(t.getMaTransCd())||
				   "1361".equals(t.getMaTransCd())||"1391".equals(t.getMaTransCd())||"1461".equals(t.getMaTransCd())||"1491".equals(t.getMaTransCd())||
				   "1461".equals(t.getMaTransCd())||"1491".equals(t.getMaTransCd())||"1561".equals(t.getMaTransCd())||"1591".equals(t.getMaTransCd())||
				   "1661".equals(t.getMaTransCd())||"1691".equals(t.getMaTransCd())){
					String rs = Utils.dealTransSt(t.getMaTransCd(),t.getTransSt());
					t.setDealRs(rs);
				}
				
				t.setKeyRsp(Constance.Null2EmptyTrim(obj[16]));
				
				tftList.add(t);
			}
		}
		} catch (Exception e) {
			logger.error("云商宝历史交易查询List解析异常：",e);
			throw new RuntimeException("云商宝历史交易查询List解析异常");
		}
		
	}
	
	@Action(value="exportEstrn",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xlsx",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/estrn/queryYsbEstrnHis.jsp") }) 
	public String  exportEstrn() throws Exception{
		logger.info("导出云商宝历史交易明细");
		Operators logingMerchant = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);

		if (searchCondition == null) {
			searchCondition = (YsbEstrnHisInfoSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new YsbEstrnHisInfoSearchCondition();
			}
		}
		if ("".equals(Constance.Null2EmptyTrim(searchCondition.getMinDate()))) {
			logger.info("云商宝历史交易导出导出条件为空");
			return "error";
		}
		try {

			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
	        String superRole= map.get("superRole");
	        String opRealId =map.get("opRealId");
	        //当登录人员为代理商时，查询他的子代理
			searchCondition.setRoleType(superRole);
			if(Role.MERCHANT.getCode().equals(superRole)){
				searchCondition.setMerNo(logingMerchant.getAccountNo());
			}else if(Role.AGENT.getCode().equals(superRole)||Role.SFB_AGENT.getCode().equals(superRole)||Role.O_MANAGER.getCode().equals(superRole)){
					
				String agentId= opRealId;
				searchCondition.setAgentId(agentId);
					
			}else if(Role.AGENT_BUSS.getCode().equals(superRole)){
				searchCondition.setOpId(opRealId);
			}else if(Role.MARKET_DIRECT.getCode().equals(superRole) || Role.MARKET_LEAD.getCode().equals(superRole)){
				searchCondition.setMarketorId(opRealId);
			}
			
			int rows = pagenitionService.countSQL(searchCondition);
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), rows);
			}

			List<TblTfrHisTrnLog> tftList = new ArrayList<TblTfrHisTrnLog>();
			Map<String, String> resMap = dealTheSearchRsListForExport(tftList,
					searchRsList);

			SXSSFWorkbook work = excelService.exportYsbHisTransFlow(tftList,
					searchCondition.getMinDate(), searchCondition.getMaxDate(),
					resMap,logingMerchant.getRoleType());

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());

		}

		return SUCCESS;
	}
	
	private Map<String,String> dealTheSearchRsListForExport(List<TblTfrHisTrnLog> tftList,
			List<Object> searchRsList) {
		Map<String,String> resMap = new HashMap<String, String>();
		BigDecimal totalAmt = new BigDecimal(0);
		int totalCount = 0;
		BigDecimal cxTotalAmt = new BigDecimal(0);
		int cxTotalCount = 0;
		try {
			
	    Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
//	    Map<String, String> transTypes=ConfigProperties.getTransTypes();
	    
		if(searchRsList!=null&&searchRsList.size()>0){
			Iterator iterator=searchRsList.iterator();
			while (iterator.hasNext()) {
				Object[] obj= (Object[])iterator.next();
				TblTfrHisTrnLog t = new TblTfrHisTrnLog();
				//主账号
				if("1".equals(logingMerchant.getAgentType())){
					t.setPriAcctNo(Constance.Null2EmptyTrim(obj[5]));
				}else{
					t.setPriAcctNo(Utils.dealCardNoTwo(Constance.Null2EmptyTrim(obj[5])));
				}
				
				t.setTransDt(Constance.Null2EmptyTrim(obj[0]));
				t.setTransMt(Constance.Null2EmptyTrim(obj[1]));
				t.setTranTp(Constance.Null2EmptyTrim(obj[2]));
				t.setRespCd(Constance.Null2EmptyTrim(obj[3]));
				t.setTransSt(Constance.Null2EmptyTrim(obj[4]));
				t.setCardType(Constant.CARD_CLASS_MAP.get(Constance.Null2EmptyTrim(obj[6])));
				t.setPmtNo(Constance.Null2EmptyTrim(obj[7]));
				t.setMchntNmConv(Constance.Null2EmptyTrim(obj[9]));
				t.setMchntCd(Constance.Null2EmptyTrim(obj[10]));
				t.setTermId(Constance.Null2EmptyTrim(obj[11]));
				t.setMaTransSeq(Long.parseLong(Constance.Null2EmptyTrim(obj[12])));
				t.setRetriRefNo(Constance.Null2EmptyTrim(obj[13]));
				t.setRespName(respondeMap.get(Constance.Null2EmptyTrim(obj[3])));
				t.setTransInf(tranMap.get(Constance.Null2EmptyTrim(obj[15])));
				t.setMchntCdConv(Constance.Null2EmptyTrim(obj[17]));
				t.setRetriRefNoConv(Constance.Null2EmptyTrim(obj[18]));
				String tra = Constance.Null2EmptyTrim(obj[8]);
				if("".equals(tra)){
					t.setTransAt("0.00");
				}else{
					BigDecimal btra = new BigDecimal(tra);
					BigDecimal bb = new BigDecimal(100);
					BigDecimal bres = btra.divide(bb,2,BigDecimal.ROUND_HALF_UP); 
					t.setTransAt(bres.toString());
				}
				
				String posEntrymd = Constance.Null2EmptyTrim(obj[14]);
				t.setPosEntryMdCd(posEntrymd);
				
				String cardClass = Constance.Null2EmptyTrim(obj[6]);
				if(posEntrymd.length()<3){
					t.setPosEntryMdCdName("未知");
				}else if("02".equals(posEntrymd.substring(0, 2))){
					t.setPosEntryMdCdName("磁条卡");
				}else if("05".equals(posEntrymd.substring(0, 2))){
					t.setPosEntryMdCdName("芯片插卡");
				}else if("07".equals(posEntrymd.substring(0, 2))){
					if("".equals(cardClass)){
						t.setPosEntryMdCdName("未知");
					}else if("0".equals(cardClass.substring(0, 1))){
						t.setPosEntryMdCdName("芯片非接");
					}else if("1".equals(cardClass.substring(0, 1))){
						t.setPosEntryMdCdName("芯片云闪付");
					}
				}else if("98".equals(posEntrymd.substring(0, 2))){
					if("".equals(cardClass)){
						t.setPosEntryMdCdName("未知");
					}else if("0".equals(cardClass.substring(0, 1))){
						t.setPosEntryMdCdName("芯片非接");
					}else if("1".equals(cardClass.substring(0, 1))){
						t.setPosEntryMdCdName("芯片云闪付");
					}
				}

				t.setMaTransCd(Constance.Null2EmptyTrim(obj[15]));
				
				if("1171".equals(t.getMaTransCd())||"1011".equals(t.getMaTransCd())||"4011".equals(t.getMaTransCd())||"2011".equals(t.getMaTransCd())||
				   "1161".equals(t.getMaTransCd())||"1191".equals(t.getMaTransCd())||"1261".equals(t.getMaTransCd())||"1291".equals(t.getMaTransCd())||
				   "1361".equals(t.getMaTransCd())||"1391".equals(t.getMaTransCd())||"1461".equals(t.getMaTransCd())||"1491".equals(t.getMaTransCd())||
				   "1461".equals(t.getMaTransCd())||"1491".equals(t.getMaTransCd())||"1561".equals(t.getMaTransCd())||"1591".equals(t.getMaTransCd())||
				   "1661".equals(t.getMaTransCd())||"1691".equals(t.getMaTransCd())){
					String rs = Utils.dealTransSt(t.getMaTransCd(),t.getTransSt());
					t.setDealRs(rs);
				}
				
				t.setKeyRsp(Constance.Null2EmptyTrim(obj[16]));
				
				if(("1171".equals(t.getMaTransCd())||"1011".equals(t.getMaTransCd())||"1191".equals(t.getMaTransCd())||"1391".equals(t.getMaTransCd())||"1491".equals(t.getMaTransCd())
						||"1591".equals(t.getMaTransCd())||"1291".equals(t.getMaTransCd())||"1691".equals(t.getMaTransCd())) && "1000000000".equals(t.getTransSt()) && "00".equals(t.getRespCd())){
					totalAmt = totalAmt.add(new BigDecimal(t.getTransAt()));
					totalCount++;
				}
				
				if("2011".equals(t.getMaTransCd()) && "1000000000".equals(t.getTransSt()) && "00".equals(t.getRespCd())){
					cxTotalAmt = cxTotalAmt.add(new BigDecimal(t.getTransAt()));
					cxTotalCount++;
				}
				
				tftList.add(t);
			}
		}
		
		resMap.put("totalAmt", totalAmt.toPlainString());
		resMap.put("totalCount", String.valueOf(totalCount));
		resMap.put("cxTotalAmt", cxTotalAmt.toPlainString());
		resMap.put("cxTotalCount", String.valueOf(cxTotalCount));
		} catch (Exception e) {
			logger.error("云商宝历史交易查询List解析异常：",e);
			throw new RuntimeException("云商宝历史交易查询List解析异常");
		}
		
		return resMap;
		
	}
	
	public void org(){
		HashMap<String , String> newResMap = new LinkedHashMap<String, String>();
		
		Set<Entry<String,String>> entrySet = respondeMap.entrySet();
		Iterator it = entrySet.iterator();
		while(it.hasNext()){
			Entry<String,String> en = (Entry<String, String>) it.next();
			String key = en.getKey();
			String value = en.getValue();
			if(!"00".equals(key)){
				newResMap.put(key, value);
			}else{
				newResMap.put(key, value);
				newResMap.put("9999", "失败");
			}
		}
		
		getRequest().setAttribute("tranMap",tranMap);
		getRequest().setAttribute("respMap",newResMap);
	}
	
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (YsbEstrnHisInfoSearchCondition)getSession().getAttribute(YSB_SEARCH_SESSION_BEAN_ESTRN_HIS);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(YSB_SEARCH_SESSION_BEAN_ESTRN_HIS, searchCondition);
	}

	public YsbEstrnHisInfoSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(YsbEstrnHisInfoSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	
	public String getExcelName() {
		String excelName="历史交易详情"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}
	



}
